<template>
  <div class="crontab-container">
    <byui-query-form>
      <byui-query-form-left-panel>
        <el-button
          type="primary"
          @click="addCrontab"
          v-if="checkPermission(['admin', 'editor'])"
          >添加任务</el-button
        >
      </byui-query-form-left-panel>
    </byui-query-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      border
    >
      <el-table-column prop="taskName" label="任务名称"> </el-table-column>
      <el-table-column prop="title" label="商品名"> </el-table-column>
      <el-table-column
        prop="parentName"
        label="团队"
        v-if="checkPermission(['root'])"
        width="160"
      ></el-table-column>
      <el-table-column
        prop="useUnion"
        label="联盟账号"
        v-if="checkPermission(['admin', 'root'])"
        width="160"
      >
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        v-if="checkPermission(['admin', 'root'])"
        width="160"
      >
      </el-table-column>
      <el-table-column prop="status" label="状态" width="180">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.status == 1"
            effect="dark"
            size="mini"
            type="success"
            >已生成</el-tag
          >
          <el-tooltip
            class="item"
            effect="dark"
            placement="left"
            style="cursor: pointer;"
            :content="scope.row.errorLog || '未知错误'"
          >
            <el-tag
              v-if="scope.row.status == -1"
              effect="dark"
              size="mini"
              type="danger"
              >生成失败</el-tag
            >
          </el-tooltip>
          <el-tag
            v-if="scope.row.status == 0"
            effect="dark"
            size="mini"
            type="info"
            >待生成</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="setTotalNum" label="淘礼金信息" width="260">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            placement="left"
            style="cursor: pointer;"
          >
            <div slot="content" style="margin: 10px; line-height: 24px;">
              =======淘礼金数据======<br />
              总数：{{ scope.row.setTotalNum }}<br />
              单个金额：{{ scope.row.setPerFace }}<br />
              每人允许领取：{{ scope.row.setUserTotalWinNumLimit }}个<br />
              领取时间：{{ scope.row.setSendTime[0] }} -
              {{ scope.row.setSendTime[1] }}<br />
              使用时间：{{ scope.row.setUseTime[0] }} -
              {{ scope.row.setUseTime[1] }}<br />
            </div>
            <div>查看详情</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="crontabTime" label="计划生成时间" width="260">
      </el-table-column>
    </el-table>

    <el-pagination
      :background="background"
      :current-page="listForm.pageNo"
      :layout="layout"
      :page-size="listForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    >
    </el-pagination>

    <el-dialog
      title="添加定时任务"
      :visible.sync="addShow"
      width="600px"
      center
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        label-width="120px"
        ref="AddForm"
        :rules="rules"
      >
        <el-row v-if="!addForm.all">
          <el-col :span="12">
            <el-form-item
              label="联盟账号"
              prop="useUnion"
              v-if="checkPermission(['admin']) && unionList.length > 0"
            >
              <el-select
                v-model="unionForAdmin"
                placeholder="请选择使用的联盟账号"
                @change="reChannelList"
              >
                <el-option
                  :label="name"
                  :value="name"
                  v-for="(name, index) in unionList"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="媒体"
              v-if="checkPermission(['admin']) && unionList.length > 0"
              label-width="60px"
            >
              <el-select
                v-model="channelForAdmin"
                placeholder="请选择使用的媒体"
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in channelList"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          label="用户名"
          prop="useUnion"
          v-if="checkPermission(['admin']) && unionList.length > 0"
        >
          <el-input
            v-model="addForm.userName"
            autocomplete="off"
            placeholder="管理员如果帮别人生成填写对应用户名, 否则留空"
            style="width: 250px;"
            :disabled="addForm.all"
          ></el-input>
          <el-checkbox v-model="addForm.all" style="margin-left: 10px;"
            >所有人</el-checkbox
          >
        </el-form-item>
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="addForm.taskName"
            autocomplete="off"
            placeholder="自己备注方便查看"
          ></el-input>
        </el-form-item>
        <el-form-item label="任务执行时间" prop="crontabTime">
          <el-date-picker
            v-model="addForm.crontabTime"
            :picker-options="pickerOptions"
            type="datetime"
            placeholder="计划生成时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="商品链接" prop="setItemId">
          <el-input
            v-model="goodsUrl"
            autocomplete="off"
            @blur="setItemId"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品名" prop="title">
          <el-input v-model="addForm.title" autocomplete="off">
            <el-button
              slot="append"
              icon="el-icon-zoom-in"
              @click.native="getGoodsTitle()"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="pic">
          <el-input v-model="addForm.pic" autocomplete="off">
            <el-button
              slot="append"
              icon="el-icon-zoom-in"
              @click.native="getGoodsTitle()"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="券链接"
          ><el-input
            v-model="addForm.couponlink"
            autocomplete="off"
            placeholder="https://uland.taobao.com/quan/detail?sellerId=***&activityId=***"
          ></el-input
        ></el-form-item>
        <el-form-item label="淘礼金名称" prop="setName"
          ><el-input v-model="addForm.setName" autocomplete="off"></el-input
        ></el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总个数" prop="setTotalNum">
              <el-input-number
                v-model="addForm.setTotalNum"
                :min="1"
                :max="500000"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单个金额" prop="setPerFace">
              <el-input-number
                v-model="addForm.setPerFace"
                :precision="2"
                :step="0.1"
                :min="1"
                :max="99999"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可领取次数" prop="setUserTotalWinNumLimit">
              <el-input-number
                v-model="addForm.setUserTotalWinNumLimit"
                :min="1"
                :max="100"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="佣金类型">
              <el-select v-model="addForm.setCampaignType">
                <el-option label="普通" value=""></el-option>
                <el-option label="定向计划" value="DX"></el-option>
                <el-option label="营销计划" value="MKT"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="领取时间" prop="setSendTime">
          <el-date-picker
            style="width: 100%;"
            v-model="addForm.setSendTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="领取开始日期"
            end-placeholder="领取结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="使用时间" prop="setUseTime">
          <el-date-picker
            style="width: 100%;"
            v-model="addForm.setUseTime"
            type="daterange"
            range-separator="至"
            start-placeholder="使用开始日期"
            end-placeholder="使用结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addShow = false">取 消</el-button>
        <el-button type="primary" @click="saveCrontab">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addCrontab,
  listCrontab,
  listUnionChannel,
  listUnionName,
} from "@/api/index";
import checkPermission from "@/utils/permission";
export default {
  name: "Crontab",
  components: {},
  data() {
    return {
      addShow: false,
      total: 0,
      background: true,
      layout: "total, sizes, prev, pager, next, jumper",
      listForm: {
        pageNo: 1,
        pageSize: 20,
      },
      goodsUrl: "",
      addForm: {
        setItemId: "",
        couponlink: "",
        setName: "",
        setTotalNum: "",
        setUserTotalWinNumLimit: "",
        setPerFace: "",
        setUseTime: [],
        setSendTime: [],
        setCampaignType: "",
        crontabTime: "",
        taskName: "",
        userName: "",
        title: "",
        pic: "",
        all: false,
      },
      rules: {
        setItemId: [
          { required: true, message: "请输入商品链接", trigger: "blur" },
        ],
        title: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        pic: [{ required: true, message: "请输入商品图片", trigger: "blur" }],
        setName: [
          {
            required: true,
            message: "请输入淘礼金名称，不超过10个字",
            trigger: "blur",
          },
        ],
        setTotalNum: [
          { required: true, message: "请输入生成数量", trigger: "blur" },
        ],
        setUserTotalWinNumLimit: [
          { required: true, message: "请输入可领取次数", trigger: "blur" },
        ],
        setPerFace: [
          { required: true, message: "请输入单个淘礼金金额", trigger: "blur" },
        ],
        setUseTime: [
          { required: true, message: "请输入使用时间", trigger: "change" },
        ],
        setSendTime: [
          { required: true, message: "请输入领取时间", trigger: "change" },
        ],
        crontabTime: [
          { required: true, message: "请输入计划生成时间", trigger: "change" },
        ],
        taskName: [
          { required: true, message: "请输入任务名称", trigger: "blur" },
        ],
      },
      unionList: [],
      unionForAdmin: "",
      channelList: [],
      channelForAdmin: "",
      pickerOptions: {
        disabledDate: this.disabledDate,
      },
      listLoading: true,
      list: [],
      elementLoadingText: "正在加载...",
    };
  },
  created() {
    if (this.checkPermission(["admin"])) {
      listUnionName({}).then((res) => {
        if (res.code && res.code === 200) {
          this.unionList = res.data;
          if (res.data.length == 0) {
            this.$baseAlert(
              "必须先添加淘宝账号才能搜索",
              "请先添加账号",
              () => {
                this.$router.push("/admin/unionTaobao");
              }
            );
          }
        }
      });
    }
    this.fetchData();
  },
  mounted() {},
  methods: {
    addCrontab() {
      this.addShow = true;
    },
    handleSizeChange(val) {
      this.listForm.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.listForm.pageNo = val;
      this.fetchData();
    },
    saveCrontab() {
      this.$refs["AddForm"].validate((valid) => {
        if (valid) {
          let setData = this.addForm;
          if (
            this.checkPermission(["admin"]) &&
            this.addForm.userName == "" &&
            this.addForm.all === false
          ) {
            if (this.unionForAdmin == "") {
              return this.$baseMessage(
                "由于您是管理员，必须选择需要生成礼金的联盟账号",
                "error"
              );
            } else {
              setData.useUnion = this.unionForAdmin;
            }
            if (this.channelForAdmin == "") {
              return this.$baseMessage(
                "由于您是管理员，必须选择需要生成礼金的媒体",
                "error"
              );
            } else {
              setData.useChannel = this.channelForAdmin;
            }
          }
          addCrontab(setData).then((res) => {
            this.$baseMessage("添加计划任务成功", "success");
            this.fetchData();
            this.addShow = false;
          });
        }
      });
    },
    reChannelList() {
      this.channelForAdmin = "";
      listUnionChannel({ unionName: this.unionForAdmin }).then((res) => {
        this.channelList = res.data.channel;
      });
    },
    fetchData() {
      listCrontab(this.listForm).then((res) => {
        this.list = res.data;
        this.total = res.totalCount;
        setTimeout(() => {
          this.listLoading = false;
        }, 500);
      });
    },
    disabledDate(value) {
      if (Date.now() >= value) {
        return true;
      }
      return false;
    },
    setItemId() {
      if (this.goodsUrl == "") {
        return this.$baseMessage("请输入商品链接", "warning");
      }
      const reg = /(id|Id|item_num_id|default_item_id|item_id|itemId|itemid|mallstItemId)\=([0-9]{1,20})/;
      let url = this.goodsUrl.match(reg);
      if (url == null || url.length < 3 || parseInt(url[2]) < 100000) {
        return this.$baseMessage("请输入正确的商品链接", "warning");
      }
      this.addForm.setItemId = url[2];
    },
    getGoodsTitle() {
      let that = this;
      if (that.addForm.setItemId == "") {
        return this.$baseMessage("请输入正确的商品链接", "warning");
      }
      jsonp({
        url:
          "https://acs.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?data=%7B%22itemNumId%22%3A%22" +
          that.addForm.setItemId +
          "%22%7D",
        success(res) {
          if (res.data && res.data.item && res.data.item.title) {
            that.addForm.title = res.data.item.title;
            that.addForm.pic = "https:" + res.data.item.images[0];
          } else {
            that.$baseMessage("商品标题获取失败", "warning");
          }
        },
      });
    },
    checkPermission,
  },
};

function jsonp({ url, success }) {
  let callbackName = `jsonp_${new Date().getTime()}`;
  let script = document.createElement("script");
  let baseUrl = `${url}&callback=${callbackName}`;
  script.src = baseUrl;
  document.body.appendChild(script);
  window[callbackName] = (res) => {
    success(res);
    delete window[callbackName];
    document.body.removeChild(script);
  };
}
</script>

<style lang="scss" scoped>
.crontab-container {
}
</style>
